package com.example.cxp_project7;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {
    private TextView textViewgx;
    private TextView textViewgy;
    private TextView textViewgz;
    private SensorManager mSensorManager;//定义一个传感器管理器
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取TextView对象
        textViewgx = (TextView) findViewById(R.id.X);
        textViewgy = (TextView) findViewById(R.id.Y);
        textViewgz = (TextView) findViewById(R.id.Z);
        //获取传感器SensorManager对象
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()) {//判断传感器类别
            case Sensor.TYPE_GRAVITY:
                float X = event.values[0];
                float Y = event.values[1];
                float Z = event.values[2];
                textViewgx.setText("x方向的重力加速度\n"+ X );
                textViewgy.setText("Y方向的重力加速度\n"+ Y );
                textViewgz.setText("Z方向的重力加速度\n"+ Z );
                break;
            default:
                break;
        }
    }
    protected void onResume() {
        super.onResume();
        //注册传感器
        mSensorManager.registerListener(this,
                mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
                SensorManager.SENSOR_DELAY_FASTEST);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);//解除监听注册
    }
}